package com.kvn.backdoor.controller;

import com.kvn.backdoor.base.TableEnum;
import com.kvn.backdoor.base.XmlDbManager;
import com.kvn.backdoor.common.BackdoorErrorCode;
import com.kvn.backdoor.common.OpResponse;
import com.kvn.backdoor.entity.DbConfig;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * Created by wangzhiyuan on 2018/8/16
 */
@RestController
@RequestMapping("/dbConfig")
@Validated
public class DbConfigController {

    @RequestMapping("/hello")
    public String hello() {
        return "hello world";
    }

    /**
     * 将选择的db保存到session中
     * @param id dbConfig的id
     * @param httpSession
     * @return
     */
    @RequestMapping("/selectDb")
    public OpResponse selectDb(@NotNull Integer id, HttpSession httpSession){
        DbConfig dbConfig = new DbConfig();
        dbConfig.setId(id);
        dbConfig = new XmlDbManager().use(TableEnum.DB_CONFIG).selectOne(dbConfig);
        if (dbConfig == null) {
            throw BackdoorErrorCode.ILLEGAL_PARAM.exp("id对应的DbConfig不存在：" + id);
        }
        httpSession.setAttribute("dbConfig", dbConfig);
        return OpResponse.suc();
    }

    @RequestMapping("/save")
    public OpResponse save(@RequestBody @NotNull DbConfig dbConfig){
        if (dbConfig.getId() == null) {
            new XmlDbManager().use(TableEnum.DB_CONFIG).insert(dbConfig);
        } else {
            new XmlDbManager().use(TableEnum.DB_CONFIG).updateById(dbConfig);
        }

        return OpResponse.suc();
    }

    @RequestMapping("/delete")
    public OpResponse delete(@NotEmpty String id) {
        new XmlDbManager().use(TableEnum.DB_CONFIG).deleteById(id);
        return OpResponse.suc();
    }

    @RequestMapping("/preUpdate")
    public OpResponse preUpdate(@NotNull Integer id){
        DbConfig dbConfig = new DbConfig();
        dbConfig.setId(id);
        dbConfig = new XmlDbManager().use(TableEnum.DB_CONFIG).selectOne(dbConfig);
        return OpResponse.suc(dbConfig);
    }

    @RequestMapping("/list")
    public OpResponse list(@SessionAttribute(value = "dbConfig", required = false) DbConfig dbConfig){
        List<DbConfig> dbConfigs = new XmlDbManager().use(TableEnum.DB_CONFIG).selectList(DbConfig.class);
        return OpResponse.suc(dbConfigs, dbConfig == null ? "" : dbConfig.getId().toString());
    }


}